<?php

class users extends Module {

	private
		$am_errorMsg = false;
		
	private static $aUserFriends = null;
	
	public function __construct () {
		parent::__construct (__CLASS__);
		
		$this->extend ('__users_ajax');
		$this->extend ('__users_mail');
		$this->extend ('__custom_users');
	}
	
	/**
	 * @return ModuleResponse
	 */
	public function __default () {
		throw new NotFound;		
	}
	
	/**
	 * Посучение нового пароля
	 * @return ModuleResponse
	 */
	public function forgot() {
		$oTypeUser = TypesController::getInstance()->getTypeByName('user');

		$response = new ModuleResponse;
		$response->setTemplate('users/forgot');
		$response->setAttribute('status', '');
		
		if (getRequest('error','bool')) {
			$response->addObject(new SystemError(lang('user_forgot_error',__CLASS__)));
			$response->setAttribute('status', 'error');
			
		}
		if (getRequest('ok','bool')) {
			$response->addObject(new SystemMessage(lang('user_forgot_ok',__CLASS__)));
			$response->setAttribute('status', 'ok');
		}
		
		if (isset($_POST['email']) && $_POST['email'] != '') {
			$sel = new Selection;
			$sel->addType($oTypeUser);
			$sel->addFilter('email', $_POST['email']);
			
			$res = $sel->getList();
			
			if (isset($res[0])) {
				$oUser = ObjectsController::getInstance()->getObject($oTypeUser, $res[0][0]);
				
				mt_srand(microtime(true));
				
				$s = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456';
				$len = mb_strlen($s) - 1;
				
				$newPass = '';
				
				for ($i = 0; $i < 8; ++$i) {
					$newPass .= $s[mt_rand(0,$len)];
				}
				
				$oUser->setValue('password', explayHash($newPass));
				$oUser->save();
				
				$this->sendNewPassword($oUser, $newPass);
				
				redirect(HTTP_HOST . '/users/forgot?ok');
			} else {
				redirect(HTTP_HOST . '/users/forgot?error');
			}
		}
		
		return $response;
	}
	
	/**
	 * Редактировать профиль текущего пользователя
	 * @return ModuleResponse
	 */
	public function edit_profile () {
		$oType = TypesController::getInstance()->getTypeByName ('user');
		$userId = ExplaySession::getUserId();
		$oUser = ObjectsController::getInstance()->getObject ($oType, $userId);

		$this->setPageTitle (lang('header_edit_profile',__CLASS__));
		
		$aErrors = false;
		
		if (getRequest ('param0') == 'save') {
			$data = $this->getRequestData ($userId, $oType);
			
			if (isset ($data['login'])) {
				unset ($data['login']); 
			}
			if (isset ($data['password'])) {
				unset ($data['password']); 
			}
			if (isset ($data['group'])) {
				unset ($data['group']); 
			}
			
			$oUser->setValues ($data);
			
			$aErrors = $this->getValidateErrors ($oUser, $oType);
			
			if (!in_array ($oUser->getValue ('gender'), array ('man','woman','other'))) {
				$aErrors['gender'] = lang ('error_edit_profile_undefined_gender',__CLASS__);
			}
			
			if (empty($aErrors['email'])) {
				$sel = new Selection;
				$sel->addType ($oType);
				$sel->addFilter ('email', $oUser->getValue ('email'));
				$sel->addFilter ('id', ExplaySession::getUserId(), '!=');
				
				if ($sel->getTotalCount () != 0) {
					$aErrors['email'] = lang('error_registration_not_unique_email',__CLASS__);
				}
			}
			
			if (count ($aErrors) == 0) {
				$oUser->setValue ('birthdate', strtotime (getRequest ('birthdate_day','int') . '.' . getRequest ('birthdate_month','int') . '.' . getRequest ('birthdate_year','int')));
				$oUser->save ();
				redirect (HTTP_HOST . '/users/edit_profile/success');
			}
		}
		
		$form = new Form ($oType, $userId);
		$form->buildFromType ();
		$form->addObjectValues ($oUser);
		if ($aErrors) {
			$form->setErrors ($aErrors);
		}
		
		$response = new ModuleResponse;
		if (getRequest ('param0') == 'success') {
			$response->addObject (new SystemMessage (lang('message_profile_saved',__CLASS__)));
		}
		$response->addObject ($form);
		$response->setTemplate ('users/editProfile');
		
		return $response;
	}
	
	/**
	 * Показать профиль пользователя
	 * @return ModuleResponse
	 */
	public function profile () {
		$typesController = TypesController::getInstance ();
		
		$userLogin = getRequest ('param0');
		
		if (mb_strlen ($userLogin) == 0) {
			throw new NotFound;
		}
		
		$oType = $typesController->getTypeByName ('user');
		
		$sel = new Selection;
		$sel->addType ($oType);
		$sel->addFilter ('login', $userLogin);
		$sel->addLimit (1);
		
		$res = $sel->getList ();
		
		if (count ($res) == 0) {
			throw new NotFound;
		}
		
		$userId = $res[0][0];
		
		$oUser = ObjectsController::getInstance()->getObject ($oType, $userId);
		
		$this->setPageTitle ($oUser->getValue ('name'));
		
		$oUser->setAttribute ('friend', in_array ($userId, self::getUserFriends ()) ? '1' : '0');
			
		$userGroup = userGroup (ExplaySession::getUser()->getValue ('group'));
		
		if ($userGroup == 'guest' || ExplaySession::getUserId () == $userId) {
			$oUser->setAttribute ('vote-allowed', '0');
		} else {
			$oUser->setAttribute ('vote-allowed', '1');
		}
				
		$response = new ModuleResponse;
		$response->setTemplate ('users/profile');
		$response->setAttribute ('user-id', $userId);
		$response->addObject ($oUser);
		
		return $response;
	}
	
	/**
	 * Авторизоваться
	 * @return ModuleResponse
	 */
	public function login () {
		if (!isset ($_POST['login']) && !isset ($_POST['password'])) {
			$response = new ModuleResponse;
			$response->addObject ('');
			$response->setTemplate ('users/login');
			return $response;
		}
		
		$this->setPageTitle (lang ('title_login', __CLASS__));
		
		$sLogin = safeSql ($_POST['login']);
		$sPassword = explayHash (safeSql ($_POST['password']));
		
		$oUserType = TypesController::getInstance()->getTypeByName ('user');
		
		$sel = new Selection;
		$sel->addType ($oUserType);
		$sel->addFilter ('login', $sLogin);
		$sel->addFilter ('password', $sPassword);
		$sel->addFilter ('group', '3', '!=');
		$sel->addLimit (1);
		
		if ($sel->getTotalCount () == 1) {
			ExplaySession::destroy ();
			cmsSetCookie ('login', $sLogin);
			cmsSetCookie ('password', $sPassword);
			
			$sReferer = getRequest ('referer');
			
			redirect (HTTP_HOST .  (mb_strlen ($sReferer) ? $referer : '/'));
		} else {
			$response = new ModuleResponse;
			$response->addObject (new SystemError (lang('error_login', __CLASS__)));
			$response->setTemplate ('users/login');
			return $response;
		}
		
		$response = new ModuleResponse;
		$response->setTemplate ('users/login');
		return $response;
	}
	
	public function admin_login() {
		if (!isset ($_POST['login']) || !isset ($_POST['password'])) {
			redirect(HTTP_HOST . '/admin');
		}
		
		$sLogin = safeSql ($_POST['login']);
		$sPassword = explayHash (safeSql ($_POST['password']));
		
		$oUserType = TypesController::getInstance()->getTypeByName ('user');
		
		$sel = new Selection;
		$sel->addType ($oUserType);
		$sel->addFilter ('login', $sLogin);
		$sel->addFilter ('password', $sPassword);
		$sel->addFilter ('group', '0');
		$sel->addLimit (1);
		
		if ($sel->getTotalCount () == 1) {
			ExplaySession::destroy ();
			cmsSetCookie ('login', $sLogin);
			cmsSetCookie ('password', $sPassword);
		}
		
		redirect (HTTP_HOST .  '/admin');
	}
	
	/**
	 * Закрыть сессию
	 * @return void
	 */
	public function logout () {
		ExplaySession::destroy ();
		redirect (HTTP_HOST . '/');
	}
	
	/**
	 * Регистрация нового пользователя
	 * @return ModuleResponse
	 */
	public function registration () {
		$oRegistrationType = TypesController::getInstance()->getTypeByName ('registration');
		
		$this->setPageTitle (lang ('title_registration', __CLASS__));
		
		$aErrors = array ();
		$aValues = array ();
		$captchaError = '';
		
		if (getRequest ('param0') == 'save') {
			$oUserType = TypesController::getInstance()->getTypeByName ('user');
			
			$aValues = $this->getRequestData('new' , $oRegistrationType);

			$oRegistration = new Object ($oRegistrationType);
			$oRegistration->setValues ($aValues);
			$oRegistration->setValue ('key', $this->generateRegistrationKey ());
			$oRegistration->setValue ('date', time ());
			$oRegistration->setValue ('password', isset ($aValues['password']) ? $aValues['password'] : '');
				
			$aErrors = $this->getValidateErrors ($oRegistration, $oRegistrationType);
									
			if (!isset ($aErrors['login'])) {
				$testSelLogin = new Selection;
				$testSelLogin->addType ($oRegistrationType);
				$testSelLogin->addType ($oUserType);
				$testSelLogin->addFilter ('login', $oRegistration->getValue ('login'));
				
				if ($testSelLogin->getTotalCount () > 0) {
					$aErrors['login'] = lang ('error_registration_not_unique_login', __CLASS__);
				}
			}
			
			if (!isset ($aErrors['login'])) {
				if (mb_strlen ($oRegistration->getValue ('login')) < 3 || mb_strlen ($oRegistration->getValue ('login')) > 15) {
					$aErrors['login'] = lang ('error_registration_login_length', __CLASS__);
				}
			}
			
			if (!isset ($aErrors['login'])) {
				if (!preg_match("#^[a-zA-Z0-9_-]+$#", $oRegistration->getValue ('login'))) {
					$aErrors['login'] = lang ('error_registration_login_format', __CLASS__);
				}
			}
			
			if (!isset ($aErrors['name'])) {
				if (mb_strlen ($oRegistration->getValue ('name')) < 3 || mb_strlen ($oRegistration->getValue ('name')) > 25) {
					$aErrors['name'] = lang ('error_registration_name_length', __CLASS__);
				}
			}
			
			if (!isset ($aErrors['email'])) {
				$testSelEmail = new Selection;
				$testSelEmail->addType ($oRegistrationType);
				$testSelEmail->addType ($oUserType);
				$testSelEmail->addFilter ('email', $oRegistration->getValue ('email'));
				
				if ($testSelEmail->getTotalCount () > 0) {
					$aErrors['email'] = lang ('error_registration_not_unique_email', __CLASS__);
				}
			}
			
			if (!isset ($aErrors['password'])) {
				if ($oRegistration->getValue ('password') != getRequest ('repeat_password')) {
					$aErrors['password'] = lang ('error_registration_passwords', __CLASS__);
				}
			}
			
			if (getRequest ('captcha') != getSession ('captcha')) {
				$captchaError = lang ('error_registration_captcha', __CLASS__);
			}
			
			if (count ($aErrors) == 0) {
				$oRegistration->setValue ('password', explayHash ($aValues['password']));
				
				$needConfirm = (bool) Regedit::getInstance()->get ("//modules/users/registration_confirm");
				
				if ($needConfirm) {			
					$oRegistration->createNew ();
					
					$this->registrationConfirm ($oRegistration);
				
					redirect (HTTP_HOST . '/users/registered');
				} else {
					$this->createUserByRegistration ($oRegistration);
								
					ExplaySession::destroy ();
					cmsSetCookie ('login', $oRegistration->getValue ('login'));
					cmsSetCookie ('password', $oRegistration->getValue ('password'));
					
					redirect (HTTP_HOST . '/users/welcome');
				}
			}
		}
		
		$form = new Form ($oRegistrationType, 'new');
		$form->buildFromType ();
		$form->setErrors ($aErrors);
		$form->setValues ($aValues);
		
		$response = new ModuleResponse;
		$response->addObject ($form);
		$response->addObject (new Array2XML ('captcha', array ('error' => $captchaError)));
		$response->setTemplate ('users/registration');
		
		return $response;
	}
	
	/**
	 * Подтверждение регистрации пользователя
	 * @return ModuleResponse
	 */
	public function confirm () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$this->setPageTitle (lang ('title_confirm', __CLASS__));
		
		$oRegType = $typesController->getTypeByName ('registration');
		
		$sKey = getRequest ('param0');
		
		$sel = new Selection;
		$sel->addType ($oRegType);
		$sel->addFilter ('key', $sKey);
		$sel->addLimit (1);
		
		$res = $sel->getList ();
		
		if (count ($res) == 1) {
			$oReg = $objectsController->getObject ($oRegType, $res[0][0]);
			
			$this->createUserByRegistration ($oReg);
						
			ExplaySession::destroy ();
			cmsSetCookie ('login', $oReg->getValue ('login'));
			cmsSetCookie ('password', $oReg->getValue ('password'));
			
			$oReg->delete ();
			
			redirect (HTTP_HOST . '/users/welcome');
		}
		
		$response = new ModuleResponse;
		$response->setTemplate ('users/badRegKey');
		return $response;
	}
	
	/**
	 * Показать страницу об успешной регистрации
	 * @return ModuleResponse
	 */
	public function registered () {
		$response = new ModuleResponse;
		$response->setTemplate ('users/registration');
		return $response;
	}
	
	/**
	 * Показать страницу об успешном подтверждении регистрации
	 * @return ModuleResponse
	 */
	public function welcome () {
		$response = new ModuleResponse;
		$response->setTemplate ('users/registration');
		return $response;
	}
	
	/**
	 * Страница настроек аватаров
	 * @return ModuleResponse
	 */
	public function avatars_manager () {
		$objectsController = ObjectsController::getInstance ();
		
		$oType = TypesController::getInstance()->getTypeByName ('avatar');
		$sUserAvatar = ExplaySession::getUser()->getValue ('avatar');
		
		$this->setPageTitle (lang('header_edit_profile',__CLASS__));
		
		if (getRequest ('upload', 'bool')) {
			$this->uploadAvatar ();
		}
		
		if (getRequest ('save', 'bool')) {
			$this->saveAvatars ();
		}
		
		$sel = new Selection;
		$sel->addType ($oType);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		
		$list = $sel->getList ();
		$aObjects = $objectsController->getObjectsList($list);
		$cnt = count ($list);
		$max = Regedit::getInstance()->get ('//modules/users/count_avatars');		
		
		$response = new ModuleResponse;
		
		$response->setAttribute ('used', $cnt);
		$response->setAttribute ('allowed', $max);
		
		if ($this->am_errorMsg) {
			$response->addObject (new SystemError ($this->am_errorMsg));
		}
		
		foreach ($aObjects as $oAvatar) {
			$oAvatar->setAttribute ('active', $oAvatar->getValue ('image') == $sUserAvatar ? '1' : '0');
			$response->addObject ($oAvatar);
		}
		
		$response->setTemplate ('users/avatarsManager');
		
		return $response;
	}
	
	/**
	 * Страница настроек сайта
	 * @return ModuleResponse
	 */
	public function site_settings () {
		$oType = TypesController::getInstance()->getTypeByName ('user_settings');
		
		$this->setPageTitle (lang('header_edit_profile',__CLASS__));
		
		$aErrors = array ();
		
		$sel = new Selection;
		$sel->addType ($oType);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		$sel->addLimit (1);
		
		$res = $sel->getList ();
		
		if (count ($res) == 0) {
			$oSettings = new Object ($oType);
			$oSettings->setValues (array ('user_id' => ExplaySession::getUserId ()));
			$oSettings->createNew ();
		} else {
			$oSettings = ObjectsController::getInstance()->getObject ($oType, $res[0][0]);
		}
		
		$response = new ModuleResponse;

		if (getRequest ('param0') == 'save') {
			$aProperties = $this->getRequestData ($oSettings->getId (), $oType);
			
			$oSettings->setValues ($aProperties);
			
			$aErrors = $this->getValidateErrors ($oSettings, $oType);
			
			if (count ($aErrors) == 0) {
				$oSettings->save ();
				$response->addObject (new SystemMessage (lang ('message_settings_saved',__CLASS__)));
			}
		}
		
		$form = new Form ($oType, $oSettings->getId ());
		$form->buildFromType ();
		$form->addObjectValues ($oSettings);
		if (count ($aErrors)) {
			$form->setErrors ($aErrors);
		}
		
		$response->addObject ($form);
		$response->setTemplate ('users/siteSettings');
		
		return $response;
	}
	
	/**
	 * Форма смены пароля
	 * @return ModuleReponse
	 */
	public function change_password () {
		$this->setPageTitle (lang('header_edit_profile',__CLASS__));
		
		$response = new ModuleResponse;
		$response->setTemplate ('users/changePassword');
		
		if (getRequest ('param0') == 'save') {			
			$oUser = ExplaySession::getUser ();
			
			$oldPass = getRequest ('old_password');
			$newPass = getRequest ('new_password');
			$repeatPass = getRequest ('repeat_password');
			
			$ok = true;
			
			if (explayHash ($oldPass) != $oUser->getValue ('password')) {
				$response->addObject (new SystemError (lang ('error_change_pass_wrong_old',__CLASS__)));
				$ok = false;
			} else {
				if ($newPass != $repeatPass) {
					$response->addObject (new SystemError (lang ('error_change_pass_not_qual',__CLASS__)));
					$ok = false;
				}
				if (trim ($newPass) == '') {
					$response->addObject (new SystemError (lang ('error_change_pass_null',__CLASS__)));
					$ok = false;
				}
			}
			
			if ($ok) {
				$hash = explayHash ($newPass);
				$login = $oUser->getValue ('login');
				
				$oUser->setValue ('password', $hash);
				$oUser->save ();
				
				ExplaySession::destroy ();
				
				cmsSetCookie ('login', $login);
				cmsSetCookie ('password', $hash);
				
				$_COOKIE['password'] = $hash;
				
				ExplaySession::init ();
				
				$response->addObject (new SystemMessage (lang ('change_pass_ok',__CLASS__)));
			}
		}
		
		return $response;
	}
	
	public function delete_profile() {
		$oType = TypesController::getInstance()->getTypeByName('user_delete');
		
		$response = new ModuleResponse;
		$response->setTemplate('users/deleteProfile');
		$response->setAttribute('deleted', 0);
		
		$sel = new Selection;
		$sel->addType($oType);
		$sel->addFilter('user_id', ExplaySession::getUserId());
		
		if ($sel->getTotalCount()) {
			$response->setAttribute('deleted', '-1');
		}
		else if (isset($_POST['delete'])) {
			$object = new Object($oType);
			$object->setValue('user_id', ExplaySession::getUserId());
			$object->createNew();
			
			$response->setAttribute('deleted', 1);
		}
		
		return $response;
	}
	
	/**
	 * Поле редактирования даты рождения пользователя
	 * @param integer $userId
	 * @return ModuleResponse
	 */
	public function getEditBirthdate ($userId) {
		if (!$oUser = ObjectsController::getInstance()->getObject (TypesController::getInstance()->getTypeByName ('user'), (int) $userId)) {
			throw new ControllerException ('User not found.');		
		}
		
		$birthdate = $oUser->getValue ('birthdate');
		
		$day = date ('j', $birthdate);
		$aDays = array ();
		for ($i = 1; $i <= 31; ++$i) {
			$aDays[]['day'] = array (
				'value' => $i,
				'selected' => $i == $day ? '1' : '0'
			);
		}
		
		$month = date ('n', $birthdate);
		$months = array ('Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
		$aMonths = array ();
		for ($i = 1; $i <= 12; ++$i) {
			$set = $i < 10 ? '0' . $i : $i;
			$aMonths[]['month'] = array (
				'value' => $set,
				'selected' => $i == $month ? '1' : '0',
				'title' => $months[$i-1]
			);
		}
		
		$year = date ('Y', $birthdate);
		$aYears = array ();
		$minYear = date('Y') - 60;
		for ($i = date ('Y')-4; $i >= $minYear; --$i) {
			$aYears[]['year'] = array (
				'value' => $i,
				'selected' => $i == $year ? '1' : '0'
			);
		}
		
		$response = new ModuleResponse;
		$response->addObject (new Array2XML ('birthdate', array (
			'days' => $aDays,
			'months' => $aMonths,
			'years' => $aYears
		)));
		
		return $response;
	}
	
	/**
	 * Загрузить аватар
	 * @return void
	 */
	private function uploadAvatar () {
		$oType = TypesController::getInstance()->getTypeByName ('avatar');
		
		$aProperties = $this->getRequestData ('new', $oType);
		
		$oAvatar = new Object ($oType);
		$oAvatar->setValue ('user_id', ExplaySession::getUserId ());
		$oAvatar->setValues ($aProperties);
		
		$aErrors = $this->getValidateErrors ($oAvatar, $oType);
		
		if (count ($aErrors) == 0) {
			$oAvatar->createNew ();
			
			if (getRequest ('setactive')) {
				$oUser = ExplaySession::getUser ();
				$oUser->setValue ('avatar', $oAvatar->getValue ('image'));
				$oUser->save ();
			}
			
			redirect (HTTP_HOST . '/users/avatars_manager');
		} else {
			$this->am_errorMsg = isset ($aErrors['image']) ?  $aErrors['image'] : lang ('error_am_upload_image', __CLASS__);
		}
	}
	
	/**
	 * Сохранить изменения аватаров
	 * @return void
	 */
	private function saveAvatars () {
		$objectsController = ObjectsController::getInstance ();
		$oType = TypesController::getInstance()->getTypeByName ('avatar');
		
		if (isset ($_POST['delete']) && is_array ($_POST['delete'])) {
			$sUserAvatar = ExplaySession::getUser()->getValue ('avatar');
			
			foreach ($_POST['delete'] as $objectId) {
				if (!$object = $objectsController->getObject ($oType, (int) $objectId)) {
					continue;
				}
				
				if ($object->getValue ('user_id') != ExplaySession::getUserId ()) {
					continue;
				}
				
				if ($object->getValue ('image') == $sUserAvatar) {
					$oUser = ExplaySession::getUser ();
					$oUser->setValue ('avatar', '');
					
					$oUser->save ();
				}
				
				$object->delete ();
				
				redirect (HTTP_HOST . '/users/avatars_manager');
			}
		}
		
		if (getRequest ('selected')) {
				if (!$object = $objectsController->getObject ($oType, getRequest ('selected', 'int'))) {
					redirect (HTTP_HOST . '/users/avatars_manager');
				}
				
				if ($object->getValue ('user_id') != ExplaySession::getUserId ()) {
					redirect (HTTP_HOST . '/users/avatars_manager');
				}
				
				$oUser = ExplaySession::getUser ();
				$oUser->setValue ('avatar', $object->getValue ('image'));
				$oUser->save ();
		}
		
		redirect (HTTP_HOST . '/users/avatars_manager');
	}
	
	/**
	 * Получить список друзей пользователя
	 * @param integer $userId id пользователя
	 * @return ModuleResponse
	 */
	public function getFriendsList ($userId) {
		$objectsController = ObjectsController::getInstance ();
		$oType = TypesController::getInstance()->getTypeByName ('friend');
		
		$sel = new Selection;
		$sel->addType ($oType);
		$sel->addFilter ('user_id', (int) $userId);
		
		$aObjects = $objectsController->getObjectsList($sel->getList ());
		
		$response = new ModuleResponse;
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	/**
	 * Получить массив друзей текущего пользователя
	 * @return array
	 */
	public static function getUserFriends () {
		if (self::$aUserFriends == null) {
			$sel = new Selection;
			$sel->addType (TypesController::getInstance()->getTypeByName ('friend'));
			$sel->addSelectedProperty ('friend_id');
			$sel->addFilter ('user_id', ExplaySession::getUserId ());
			
			$res = $sel->getList ();
			
			self::$aUserFriends = array ();
			
			foreach ($res as $row) {
				self::$aUserFriends[] = $row['friend_id'];
			}
		}
		
		return self::$aUserFriends;
	}
	
	/**
	 * Создать объект пользователя из объекта регистрации
	 * @param Object $oReg объект регистрации
	 * @return void
	 */
	private function createUserByRegistration (Object $oReg) {
		$oNewUser = new Object (TypesController::getInstance()->getTypeByName ('user'));
		$oNewUser->setValue ('login', $oReg->getValue ('login'));
		$oNewUser->setValue ('password', $oReg->getValue ('password'));
		$oNewUser->setValue ('name', $oReg->getValue ('name'));
		$oNewUser->setValue ('email', $oReg->getValue ('email'));
		$oNewUser->setValue ('date', $oReg->getValue ('date'));
		$oNewUser->setValue ('group', 2);
		
		$oNewUser->createNew ();
	}
	
	private function generateRegistrationKey () {
		return explayHash (time()+mt_rand(0,99));
	}

}